"""
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). 
"""

class Solution:
    # @param triangle, a list of lists of integers
    # @return an integer
    def minimumTotal(self, triangle):
        if not triangle:
            return 0

        sums = [0] * len(triangle)
        sums[0] = triangle[0][0]

        for i in range(1, len(triangle)):
            j = i
            while j >= 0:

                if j == 0:
                    sums[j] = sums[j]
                elif j == len(triangle[i])-1:
                    sums[j] = sums[j-1]
                else:
                    sums[j] = min(sums[j], sums[j-1])
                
                sums[j] += triangle[i][j]
                j -= 1

        ans = sums[0]
        for i in range(1, len(sums)):
            ans = min(ans, sums[i])
        return ans

if __name__ == '__main__':
    print Solution().minimumTotal([ [2], [3,4], [6,5,7], [4,1,8,3] ])

